package com.android.phoenix.activity.location;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.phoenix.Constant;
import com.android.phoenix.MainApplication;
import com.android.phoenix.R;
import com.android.phoenix.models.SportRecord;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.comapi.mapcontrol.BNMapController;
import com.baidu.navisdk.comapi.routeplan.BNRoutePlaner;
import com.baidu.navisdk.comapi.tts.BNTTSPlayer;
import com.baidu.navisdk.comapi.tts.BNavigatorTTSPlayer;
import com.baidu.navisdk.comapi.tts.IBNTTSPlayerListener;
import com.baidu.navisdk.model.datastruct.LocData;
import com.baidu.navisdk.model.datastruct.SensorData;
import com.baidu.navisdk.ui.routeguide.BNavigator;
import com.baidu.navisdk.ui.routeguide.IBNavigatorListener;
import com.baidu.navisdk.ui.widget.RoutePlanObserver;
import com.baidu.navisdk.ui.widget.RoutePlanObserver.IJumpToDownloadListener;
import com.baidu.nplatform.comapi.map.MapGLSurfaceView;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SportNaviActivity extends Activity implements OnClickListener {
	private ImageView title_Imgbtn_left_up;
	private TextView title_txt_center;
	private TextView title_txt_right_up;
	private TextView txt_sport_time;
	private TextView txt_sport_distance;
	private TextView txt_sport_calories;
	private TextView txt_sport_speed;
	private TextView txt_sport_heart_rate;
	private TextView txt_sport_pedaling;
	private TextView txt_sport_elevation;
	private TextView txt_sport_slope_away;
	private Button btn_sport_start_and_finish;
	private FrameLayout mapview_layout;

	private List<LatLng> listLatLngs = new ArrayList<LatLng>();

	private int getAllPointsDistance = 0;
	private MapGLSurfaceView nMapView;
	ArrayList<String> listRouteDesNodes = new ArrayList<String>();

	private boolean isStarting = false;
	private LatLng temStartPoint = null;
	private LatLng temEndPoint = null;
	private double temTwoPointsDistance = 0;
	private List<LatLng> listLatLngsTemSave = new ArrayList<LatLng>();
	private String recordID = "";
	private String recordCalorie = "";
	private String recordDate = "";
	private String recordStartTime = "";
	private String recordEndTime = "";
	private String recordDistance = "";
	private static long startTime = 0;
	private static long endTime = 0;
	private Map<String, String> MsgMap = new HashMap<String, String>();

	private SportRecord record;
	private static final int LOCATION_DATE = 1;

	private boolean flag = true;

	/**
	 * 记录最大速度，最小速度，平均速度等。。。
	 * 
	 */
	private float maxSpeed = 0;
	private float minSpeed = 0;
	private List<Float> listSpeeds = new ArrayList<Float>();

	private float maxAltitude = 0;
	private float minAltitude = 0;
	private float totalAltitude = 0;
	private float averageAltitude = 0;
	private List<Float> listAltitude = new ArrayList<Float>();

	private int maxHeartRate = 0;
	private int minHeartRate = 0;
	private int totalHeartRate = 0;
	private int index = 0;
	private List<Integer> listHeartRate = new ArrayList<Integer>();

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Map<String, String> map = new HashMap<String, String>();
			switch (msg.what) {
			case LOCATION_DATE:
				map = (Map<String, String>) msg.obj;
				if (map != null) {
					if (Float.valueOf(map.get("PointsDistance")) >= 1000) {
						txt_sport_distance.setText(String.format("%sKM",
								Integer.valueOf(map.get("PointsDistance"))
										/ 1000.0f + ""));
					} else {
						txt_sport_distance.setText(String.format("%sM",
								Float.valueOf(map.get("PointsDistance")) + ""));
					}
					txt_sport_speed.setText(String.format("%sKM/h",
							map.get("speed")));
					txt_sport_time.setText(LocationUtils.countTime(startTime,
							endTime));
					txt_sport_elevation.setText(String.format("%sM",
							map.get("Altitude")));

					txt_sport_calories.setText(LocationUtils
							.countCalories(Float.parseFloat(map
									.get("PointsDistance"))));
					txt_sport_heart_rate
							.setText(LocationUtils.countHeartRate());
					txt_sport_pedaling.setText(LocationUtils.countPedaling(
							Float.parseFloat(map.get("PointsDistance")),
							Float.parseFloat(map.get("speed"))));

					int heart_rate = Integer.parseInt(LocationUtils
							.countHeartRate());
					;
					if (maxHeartRate < heart_rate) {
						maxHeartRate = heart_rate;
					}
					if (minHeartRate > heart_rate) {
						minHeartRate = heart_rate;
					}
					totalHeartRate += heart_rate;

					if (index % 20 == 0) {
						// 处理存储数据
						Toast.makeText(SportNaviActivity.this,
								"第" + index + "次", 1).show();
						listHeartRate.add(totalHeartRate / index);
					}
					MsgMap.clear();
				}

				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acti_sport_navi);
		// 初始化titleBar；
		initTitleBar();
		initView();
		initMapView();

	}

	/**
	 * 
	 * @Title: initMapView
	 * @Description: TODO(实例化地图导航一些参数)
	 * @author: wWX230766
	 * @date: 2015-1-12 下午3:48:14
	 */
	private void initMapView() {
		// TODO Auto-generated method stub
		// 创建NmapView
		if (Build.VERSION.SDK_INT < 14) {
			BaiduNaviManager.getInstance().destroyNMapView();
		}
		nMapView = BaiduNaviManager.getInstance().createNMapView(this);
		Bundle bundle = getIntent().getExtras();
		listRouteDesNodes = bundle.getStringArrayList("nodes");


		// 创建导航视图
		View navigatorView = BNavigator.getInstance().init(
				SportNaviActivity.this, bundle, nMapView);

		mapview_layout = (FrameLayout) this.findViewById(R.id.mapview_layout);
		mapview_layout.addView(navigatorView);
		BNavigator.getInstance().setListener(mBNavigatorListener);
		BNavigator.getInstance().startNav();

		// 初始化TTS. 开发者也可以使用独立TTS模块，不用使用导航SDK提供的TTS
		BNTTSPlayer.initPlayer();
		// 设置TTS播放回调
		BNavigatorTTSPlayer.setTTSPlayerListener(new IBNTTSPlayerListener() {

			@Override
			public int playTTSText(String arg0, int arg1) {
				// 开发者可以使用其他TTS的API
				return BNTTSPlayer.playTTSText(arg0, arg1);
			}

			@Override
			public void phoneHangUp() {
				// 手机挂断
			}

			@Override
			public void phoneCalling() {
				// 通话中
			}

			@Override
			public int getTTSState() {
				// 开发者可以使用其他TTS的API,
				return BNTTSPlayer.getTTSState();
			}
		});

		BNRoutePlaner.getInstance().setObserver(
				new RoutePlanObserver(this, new IJumpToDownloadListener() {

					@Override
					public void onJumpToDownloadOfflineData() {
						// TODO Auto-generated method stub

					}
				}));
	}

	private IBNavigatorListener mBNavigatorListener = new IBNavigatorListener() {

		@Override
		public void onYawingRequestSuccess() {
			// TODO 偏航请求成功

		}

		@Override
		public void onYawingRequestStart() {
			// TODO 开始偏航请求

		}

		@Override
		public void onPageJump(int jumpTiming, Object arg) {
			// TODO 页面跳转回调
			if (IBNavigatorListener.PAGE_JUMP_WHEN_GUIDE_END == jumpTiming) {
				finish();
			} else if (IBNavigatorListener.PAGE_JUMP_WHEN_ROUTE_PLAN_FAIL == jumpTiming) {
				finish();
			}
		}

		@Override
		public void notifyGPSStatusData(int arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void notifyLoacteData(LocData locData) {
			// TODO Auto-generated method stub
			if (isStarting) {
				LatLng ll = new LatLng(locData.latitude, locData.longitude);
				if (ll == null) {
					return;
				}
				listLatLngs.add(ll);
				if (flag) {
					if (listLatLngs.size() > 9) {
						flag = false;
					}
					return;
				}

				// ===============数据处理============
				if (maxSpeed < locData.speed) {
					maxSpeed = locData.speed;
				}
				if (maxAltitude < locData.altitude) {
					maxAltitude = (float) locData.altitude;
				}
				if (minAltitude > locData.altitude) {
					minAltitude = (float) locData.altitude;
				}
				totalAltitude += locData.altitude;
				index = listLatLngs.size();
				if (index % 20 == 0) {
					averageAltitude = totalAltitude / index;
					listAltitude.add(averageAltitude);
					listSpeeds.add(locData.speed);
				}

				// 前几个点的跳跃性特别大 对计算距离有影响
				if (listLatLngs.size() > 10 && listLatLngs.size() < 10000) {
					// 计算距离，10秒内没走到一米不算
					temStartPoint = listLatLngs.get(listLatLngs.size() - 2);
					temEndPoint = listLatLngs.get(listLatLngs.size() - 1);
					temTwoPointsDistance = DistanceUtil.getDistance(
							temStartPoint, temEndPoint);
					if (temTwoPointsDistance > 1) {
						getAllPointsDistance += temTwoPointsDistance;
					}
				}
				// 取到100个点 存一次 在退出时得判断是否还有点可以存储,使用spit时最后一个是空 切记！！！！
				if (listLatLngs.size() % 100 == 0) {
					listLatLngsTemSave.addAll(listLatLngs);
					// save(String latitude,String longitude);
					if (listLatLngsTemSave != null) {
						MySaveThread thread = new MySaveThread(recordID,
								listLatLngsTemSave);
						new Thread(thread).start();
					} else {
						Toast.makeText(SportNaviActivity.this, "记录失败！。",
								Toast.LENGTH_SHORT).show();
					}
				}

				DecimalFormat df = new DecimalFormat("0.0");

				MsgMap.put("speed", String.valueOf(df.format(locData.speed)));
				MsgMap.put("PointsDistance",
						String.valueOf(df.format(getAllPointsDistance)));
				// 海拔
				MsgMap.put("Altitude", String.valueOf(locData.altitude));
				Message msg = Message.obtain();
				msg.obj = MsgMap;
				msg.what = LOCATION_DATE;
				handler.handleMessage(msg);

				endTime = System.currentTimeMillis();
			}

		}

		@Override
		public void notifyNmeaData(String arg0) {
			// TODO Auto-generated method stub

		}

		@Override
		public void notifySensorData(SensorData sensorData) {
			// TODO Auto-generated method stub
		}

		@Override
		public void notifyStartNav() {
			// TODO Auto-generated method stub
			BaiduNaviManager.getInstance().dismissWaitProgressDialog();
		}

		@Override
		public void notifyViewModeChanged(int arg0) {
			// TODO Auto-generated method stub

		}

	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		BNavigator.getInstance().resume();

		super.onResume();
		BNMapController.getInstance().onResume();
	}

	/**
	 * 
	 * @Title: initTitleBar
	 * @Description: TODO(设置统一的titleBar)
	 * @author: wWX230766
	 * @date: 2015-1-6 下午10:00:48
	 */
	private void initTitleBar() {
		title_txt_center = (TextView) this.findViewById(R.id.title_txt_center);
		title_txt_center.setText(getResources().getString(
				R.string.label_sport_navi));
		title_Imgbtn_left_up = (ImageView) this
				.findViewById(R.id.title_Imgbtn_left_up);
		title_Imgbtn_left_up.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		title_txt_right_up = (TextView) this
				.findViewById(R.id.title_txt_right_up);
		title_txt_right_up.setText(R.string.label_sport_details);
		title_txt_right_up.setOnClickListener(this);
	}

	private void initView() {
		txt_sport_time = (TextView) this.findViewById(R.id.txt_sport_time);
		txt_sport_distance = (TextView) this
				.findViewById(R.id.txt_sport_distance);
		txt_sport_calories = (TextView) this
				.findViewById(R.id.txt_sport_calories);
		txt_sport_speed = (TextView) this.findViewById(R.id.txt_sport_speed);
		txt_sport_heart_rate = (TextView) this
				.findViewById(R.id.txt_sport_heart_rate);
		txt_sport_pedaling = (TextView) this
				.findViewById(R.id.txt_sport_pedaling);
		txt_sport_elevation = (TextView) this
				.findViewById(R.id.txt_sport_elevation);
		txt_sport_slope_away = (TextView) this
				.findViewById(R.id.txt_sport_slope_away);
		btn_sport_start_and_finish = (Button) this
				.findViewById(R.id.btn_sport_start_and_finish);
		btn_sport_start_and_finish.setOnClickListener(this);
	}

	@Override
	public void onPause() {
		BNavigator.getInstance().pause();
		super.onPause();
		BNMapController.getInstance().onPause();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		BNavigator.getInstance().onConfigurationChanged(newConfig);
		super.onConfigurationChanged(newConfig);
	}

	public void onBackPressed() {
		BNavigator.getInstance().onBackPressed();
	}

	@Override
	public void onDestroy() {
		BNavigator.destory();
		BNRoutePlaner.getInstance().setObserver(null);
		Intent broadcastIntent = new Intent(Constant.END_NAVI_BROADCAST);
		sendBroadcast(broadcastIntent);
		super.onDestroy();
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btn_sport_start_and_finish:
			if (isStarting) {
				btn_sport_start_and_finish.setText(R.string.btn_sport_start);
				isStarting = false;

				// 完成运动后，剩余的点也存起来
				if (listLatLngs.size() % 100 != 0 && listLatLngs.size() > 0) {
					// save(String latitude,String longitude);
					listLatLngsTemSave.addAll(listLatLngs);
					if (listLatLngsTemSave != null
							&& listLatLngsTemSave.size() > 0) {
						MySaveThread thread = new MySaveThread(recordID,
								listLatLngsTemSave);
						new Thread(thread).start();
					}
				}
				// 设置终止时间
				recordEndTime = System.currentTimeMillis() + "";
				record.setEndTime(recordEndTime);
				// 设置卡路里
				recordCalorie = txt_sport_calories.getText().toString()
						.replace("千卡", "");
				record.setCalorie(recordCalorie);
				// 设置运动距离
				recordDistance = getAllPointsDistance / 1000.0f + "";
				record.setDistance(recordDistance);
				try {
					MainApplication.getDataHelper(SportNaviActivity.this)
							.getSportRecordDao().createOrUpdate(record);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(SportNaviActivity.this, e.toString(),
							Toast.LENGTH_SHORT).show();
				}

				if (listSpeeds.size() > 0 && listAltitude.size() > 0
						&& listHeartRate.size() > 0) {

					StringBuffer sb = new StringBuffer();
					// 15,18,20,22,13;50,22,60,50,45;90,120,130,140,150;
					// 速度，速度，速度，速度；海拔，海拔，海拔，海拔；心率，心率，心率，心率；
					for (int i = 0; i < listSpeeds.size(); i++) {
						sb.append(listSpeeds.get(i));
						sb.append(",");
					}
					sb.append(";");
					for (int j = 0; j < listAltitude.size(); j++) {
						sb.append(listAltitude.get(j));
						sb.append(",");
					}
					sb.append(";");
					for (int k = 0; k < listHeartRate.size(); k++) {
						sb.append(listHeartRate.get(k));
						sb.append(",");
					}
					LocationUtils.saveToFile(recordID + "a", sb.toString());
				}

			} else {
				btn_sport_start_and_finish.setText(R.string.btn_sport_finish);
				startTime = System.currentTimeMillis();
				isStarting = true;

				// 运动记录的对象
				record = new SportRecord();
				// 传入ID 格式：20150126111652
				record = new SportRecord();
				// 传入ID 格式：20150126111652
				recordID = LocationUtils.getCurrentTime();
				record.setId(recordID);
				// 传入date 格式：2015/01/27
				recordDate = LocationUtils.getCurrentDate();
				record.setDate(recordDate);
				// 传入开始时间 格式：11:22:56
				record.setStartTime(startTime + "");
				// record.setStartTime(recordStartTime);
			}
			break;
		case R.id.title_txt_right_up:
			if (listRouteDesNodes != null) {
				Bundle iBundle = new Bundle();
				iBundle.putStringArrayList("nodes", listRouteDesNodes);
				Intent it = new Intent(SportNaviActivity.this,
						SportNaviDetailActivity.class);
				it.putExtras(iBundle);
				startActivity(it);
			} else {
				Toast.makeText(SportNaviActivity.this, "获取百度地图数据失败！", 1).show();
			}
			break;
		}
	}

	private class MySaveThread implements Runnable {
		private List<LatLng> mlistLatLngs;
		String dateName = "";
		StringBuilder sb = new StringBuilder();

		public MySaveThread(String dateName, List<LatLng> listLatLngs) {
			this.dateName = dateName;
			mlistLatLngs = listLatLngs;
		}

		@Override
		public void run() {

			for (int j = 0; j < mlistLatLngs.size(); j++) {
				if (j % 5 == 0) {
					sb.append(mlistLatLngs.get(j).latitude);
					sb.append(":");
					sb.append(mlistLatLngs.get(j).longitude);
					sb.append(";");
				}
			}
			// TODO Auto-generated method stub
			LocationUtils.saveToFile(dateName, sb.toString());
			listLatLngsTemSave.clear();
		}

	}
}
